package com.zhongli.devplatform.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.bean.PageVO;
import com.zhongli.devplatform.bean.SecurityHelper;
import com.zhongli.devplatform.dto.teacher.NoticeDTO;
import com.zhongli.devplatform.po.common.ReadClazzNoticePO;
import com.zhongli.devplatform.po.common.ReadClazzPO;
import com.zhongli.devplatform.po.common.ReadNoticePO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.query.teacher.ReadNoticeQuery;
import com.zhongli.devplatform.service.imp.teacher.ReadClazzNoticeService;
import com.zhongli.devplatform.service.imp.common.ReadClazzService;
import com.zhongli.devplatform.service.imp.teacher.ReadNoticeService;
import com.zhongli.devplatform.service.imp.user.ReadUserService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.vo.common.NoticeVO;
import com.zhongli.devplatform.bean.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WuXiCheng
 * @version 1.0
 * @date 2020/7/23 14:49
 */
@Api(tags = "公告", description = "公告", value = "公告")
@RestController
@RequestMapping("/user/teacher")
public class NoticeController {

    @Autowired
    private ReadNoticeService noticeService;

    @Autowired
    private ReadUserService readUserService;

    @Autowired
    private ReadClazzService clazzService;

    @Autowired
    private ReadClazzNoticeService clazzNoticeService;

    /**
     * 分页查询(排序)
     * @param noticeQuery 查询对象
     * @return 返回pageList
     */
    @ApiModelProperty("分页查询(排序)")
    @GetMapping("/listPage")
    public PageVO<ReadNoticePO> listChapter(@ModelAttribute ReadNoticeQuery noticeQuery){
        return noticeService.loadPageList(noticeQuery);
    }


    @ApiModelProperty("修改状态")
    @PostMapping("/update/{id}")
    public Res<String> updateStatus(@PathVariable Integer id){
        Integer userId = SecurityHelper.getCurrentUserId();
        ReadNoticePO noticePO = noticeService.getById(id);
        if (StringUtils.hasLength(noticePO.getNotifiedPersonIds())){
            noticePO.setNotifiedPersonIds(noticePO.getNotifiedPersonIds() + ":" + userId);
        }else {
            noticePO.setNotifiedPersonIds(userId.toString());
        }
        noticeService.updateById(noticePO);
        return Res.ok("success");
    }



    /**
     * 列表
     */
    @ApiModelProperty("列表")
    @GetMapping("/list")
    public Res list(@ModelAttribute ReadNoticeQuery noticeQuery){
        Integer userId = SecurityHelper.getCurrentUserId();
        List<ReadNoticePO> noticePOS = noticeService.list(new QueryWrapper<ReadNoticePO>()
                .eq(noticeQuery.getNoticeType() !=null,"notice_type",noticeQuery.getNoticeType())
                .eq("publisher",userId)
                .orderByDesc("release_time")
                .orderByDesc("status"));
        List<NoticeVO> data = BeanCopierUtil.copy(noticePOS, NoticeVO.class);
        return Res.ok(data);
    }


    /**
     * 列表
     */
    @ApiModelProperty("学生通知列表")
    @GetMapping("/stuNotice")
    public Res<List<NoticeVO>> stuNotice(@ModelAttribute ReadNoticeQuery noticeQuery){
        Integer userId = SecurityHelper.getCurrentUserId();
        ReadUserPO user = readUserService.getById(userId);
        List<ReadClazzNoticePO> clazzNoticePOS = clazzNoticeService.
                list(new QueryWrapper<ReadClazzNoticePO>().eq("clazz_id", user.getClazzId()));
        List<Integer> noticeIds = clazzNoticePOS.stream().map(ReadClazzNoticePO::getNoticeId).collect(Collectors.toList());
        if (noticeIds.isEmpty()) return Res.ok(null);
        List<ReadNoticePO> noticePOS = noticeService.list(new QueryWrapper<ReadNoticePO>()
                .eq(noticeQuery.getNoticeType() !=null,"notice_type",noticeQuery.getNoticeType())
                .in("id",noticeIds)
                .orderByAsc("status")
                .orderByDesc("release_time"));
        noticePOS.forEach(item -> {
            if (StringUtils.hasLength(item.getNotifiedPersonIds())){
                item.setStatus(item.getNotifiedPersonIds().contains(userId.toString()));
            }else {
                item.setStatus(false);
            }

        });
        List<NoticeVO> data = BeanCopierUtil.copy(noticePOS, NoticeVO.class);
        return Res.ok(data);
    }


    @ApiOperation("根据id 查询通知")
    @GetMapping("/{id}")
    public Res getOne(@PathVariable Integer id){
        ReadNoticePO data = noticeService.getById(id);
        return Res.ok(data);
    }


    @ApiModelProperty("发布通知")
    @PostMapping("/publish")
    public Res<String> publishNotice(@RequestBody NoticeDTO noticeDTO){
        if (noticeDTO.getClazzId().isEmpty() && StringUtils.isEmpty( noticeDTO.getNoticeType())){
            return Res.not_ok("通知群体,通知类型不能为空");
        }
        ReadNoticePO noticePO = BeanCopierUtil.copy(noticeDTO, ReadNoticePO.class);
        assert noticePO != null;
        noticePO.setReleaseTime(new Date());
        noticePO.setPublisher(SecurityHelper.getCurrentUserId());
        noticeService.save(noticePO);

        List<ReadClazzPO> clazzPOS = clazzService.listByIds(noticeDTO.getClazzId());
        for (ReadClazzPO clazzPO : clazzPOS) {
            ReadClazzNoticePO clazzNoticePO = new ReadClazzNoticePO();
            clazzNoticePO.setClazzId(clazzPO.getId());
            clazzNoticePO.setNoticeId(noticePO.getId());
            clazzNoticeService.save(clazzNoticePO);
        }

        return Res.ok("success");
    }
}
